import requests
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from util import *
source_id = 1
url = f'https://weibo.com/ajax/statuses/hot_band'
headers = {
    'accept': ' application/json, text/plain, */*',
    'accept-encoding': ' gzip, deflate, br',
    'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,it;q=0.6',
    'client-version': ' v2.34.64',
    'cookie': 'SINAGLOBAL=3746057303235.7944.1649234819078; UOR=,,www.baidu.com; '
              'SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9W5zBTB0lrGyFiEZSs4SJADU5JpX5KMhUgL.Fozf1K.RSoqNS052dJLoI7UP'
              '-.4Pg8ik; ALF=1689039626; SSOLoginState=1657503628; '
              'SCF=AvHA7Mffi_w4lGMkb9Sd00wB2z-1wkhc0zgas4AZgXmrnmKu1noBdj4zpec8uyEPP7hRpivv9qVG2G7jZU-i_Pk.; '
              'SUB=_2A25Pzw_dDeRhGeRL4lsZ9ijLzDyIHXVsvWYVrDV8PUNbmtANLUvEkW9NUwh0xxRmdJN2HO93aUzGT0G2aZmoLORq; '
              'XSRF-TOKEN=2_TVfCdh-8MhlsA4wcGz-wgN; PC_TOKEN=5c7c1a4ce5; _s_tentry=weibo.com; '
              'Apache=633189417698.5697.1657506716800; '
              'ULV=1657506717018:16:3:1:633189417698.5697.1657506716800:1657074129996; '
              'WBPSESS=oMUqrkFEUSzvkYxa1JiOpbZsRWBWLnipJ4-_2vbXKcGVe1b9wv9DJJHuL2AU5tN7RlZTvelUHa05DQqDs'
              '-GA2VZwmL_n4q7_BKDiAjbGbam1mvJw7SN17AIX043Pj8aETxi9mI4fcGWHD-Bz7G1sJQ==',
    'referer': ' https://weibo.com/hot/search',
    'sec-ch-ua': 'Not/A)Brand;v=99, Google Chrome;v=103, Chromium;v=103',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': 'Windows',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'server-version': 'v2022.07.08.3',
    'traceparent': '00-42b3306d0fd063b8851df7b094454aba-acca2248dd2e54a4-00',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 '
                  'Safari/537.36',
    'x-requested-with': 'XMLHttpRequest',
    'x-xsrf-token': '2_TVfCdh-8MhlsA4wcGz-wgN'
}


def wb_search():
    requests.session()
    response = requests.get(url, headers)
    response.encoding = 'UTF-8'
    response_data = response.text
    response_data = dict(json.loads(response_data))
    hot_words = []
    params = (
        "id", "source_id", "title", "is_hot", "is_fei", "is_new", "create_time", "hot_index", "category",
        "onboard_time",
        "info_complete")
    if "ok" in response_data.keys() and response_data['ok'] == 1:
        band_list = response_data['data']['band_list']
        create_time = str(int(time.time()))
        for val in band_list:
            val = dict(val)
            if "ad_channel" in val.keys():
                continue
            item = {
                "id": int(unique_id()),
                "source_id": source_id,
                "title": val['word'],
                "is_hot": int("is_hot" in val.keys()),
                "is_fei": int("is_fei" in val.keys()),
                "is_new": int("is_new" in val.keys()),
                "create_time": create_time,
                "hot_index": val['raw_hot'],
                "category": val['category'],
                "onboard_time": str(int(val['onboard_time'])),
                "info_complete": 1
            }
            hot_words.append(item)
        flag = insert_hot_words(params=params, hot_words=hot_words)
        return flag
    return []



if __name__ == "__main__":
    try:
        data_list = wb_search()
        if type(data_list) == list and len(data_list) > 0:
            print('微博热词搜索结束')
            baidu_search(data_list)
        elif type(data_list) == list and len(data_list) == 0:
            print('微博搜索结果为空;未进行百度搜索')
        else:
            print('微博搜索失败;未进行百度搜索')
    except Exception as e:
        print(f"\033[1;31m{e}\033[0m")
